package com.wisdom.core.netty.handler.client;

import com.alibaba.fastjson.JSON;
import com.wisdom.core.data.RpcResponse;
import com.wisdom.core.exception.RpcException;
import com.wisdom.core.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @description: <将字节数组解码为RpcResponse对象>
 * @author: Leo
 * @date: 2021-08-23 19:23
 */
@Slf4j
public class RpcResponseDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception {
        try {
            //获取请求体的字节长度
            int length = byteBuf.readableBytes();
            //将请求体写入字节数组
            byte[] bytes = new byte[length];
            byteBuf.readBytes(bytes);
            RpcResponse response  = ProtostuffUtil.deserialize(bytes, RpcResponse.class);
            log.info("client received response, response is {}", JSON.toJSONString(response));
            out.add(response);

        } catch (Exception e) {
            log.error("RpcResponseDecoder decode error, msg is {}", e.getMessage());
            throw new RpcException(e.getMessage(), e);
        }
    }
}
